<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use App\Models\Admin\User;
use App\Models\Admin\Order;
use App\Models\Admin\Grade;
use DB, Auth;
use App\Models\Admin\DealRecord;
use App\Models\Admin\TeamAward;
use App\Models\Admin\TotalBonusPool;
use App\Models\Admin\DailyAmount;
use App\Exports\OnePoolExport;
use Excel;
use App\Exports\DailyAmountExport;
use App\Exports\BdMemPoolExport;
use App\Exports\BdOrderPoolExport;
use App\Exports\UserTemplateExport;
use App\Imports\UserImport;


class MemberController extends Controller
{
    // 军功章显示
    public function jgz_list(Request $request)
    {
        // 读取店铺ID
        $user = Auth::guard('admin')->user();
        if ($user->store_id === 0) {
            // 超管必需选择店铺
            $store_id = $request['storeId'];
            if (empty($store_id)) {
                return self::errorClient(['info' => '请输入店铺ID'.$store_id]);
            }
        } else {
            // 否则 获取用户本身代表的店铺
            $store_id = $user->store_id;
        }
        $User = new User;
        $Order = new Order;
        $deal = new DealRecord;
        $beg = date('Y-m-1 00:00:00',strtotime('last month'));
        $end = date('Y-m-d 23:59:59',strtotime(date('Y-m-1').'-1 day'));
        
        $min_level_arr = TeamAward::where('store_id', $store_id)->first();

        $user_send = $deal->join('users as u','u.id',"=",'deal_records.user_id')
         ->where('deal_records.store_id',$store_id)->where('deal_records.jm_type',3)->where('deal_records.status',3)->where('deal_records.is_set',0)->whereBetween('deal_records.created_at',[$beg, $end])
         ->groupBy('deal_records.user_id')
         ->select('u.id',DB::raw('SUM(deal_records.amount) as amountSum'),'u.gold','u.grade','u.jgz','u.grade_at','u.is_partner','u.partner_at')
         ->get()->toArray();
        
        $userIds = [];
        foreach ($user_send as $key => $value) {
            //VIP
                if($value['grade'] >= $min_level_arr['min_level'] && $value['grade_at'] <= $end){
                    //需要发放奖金的用户
                    array_push($userIds,$value['id']);
                }
                //合伙人
                if($value['is_partner'] == 1 && $value['partner_at'] <= $end){
                    //需要发放奖金的用户
                    array_push($userIds,$value['id']);
                }
        }
        $userIds = array_unique($userIds);
        $amountSum = $deal->whereIn('user_id',$userIds)->where('store_id',$store_id)->where('jm_type',3)->where('status',3)->where('is_set',0)->whereBetween('created_at',[$beg, $end])->sum('amount');
        $amountSum = $amountSum/100;
        if ($amountSum == 0) {
            return self::errorClient(['info' => $min_level_arr['award_name'].'为0，无可发放内容']);
        }
        
        $grade = new Grade;
        $gradeInfo = $grade->gradeOptions($store_id);
        //上个月总奖金  1号奖金池总计
        $poolModel = $deal->where('store_id',$store_id)->whereIn('deal_type',[21,30])->where('status',3)->where('is_set',0)->whereBetween('created_at',[$beg, $end]);
        $poolSum = $poolModel->sum('amount');
        $poolSum = $poolSum/100;

        //保留两位小数  不四舍五入  小数位取小数点后两位
        $num = ($poolSum/$amountSum)*1000;
        if($num >= 1){
            $person_get = floor($num)/1000;
        }else{
            $person_get = 0;
        }
    
        $send_reward = 0;// 发放出的奖金, 与应发放奖金有一定的差值, 得到差值 并 进行处理
        $arr = [];
        foreach ($user_send as $key => $value) {
                        $self_jgz = $value['amountSum'] / 100;
                        $arr[$key]['store_id'] = $store_id;
                        $arr[$key]['id'] = $value['id'];
                        $arr[$key]['grade'] = '会员';
                        $arr[$key]['jgz'] = $self_jgz;
                        $arr[$key]['reward'] = 0;
                if(in_array($value['id'],$userIds)){
                        $arr[$key]['grade'] = $gradeInfo[$value['grade']]['label'];
                        // 遍历得出 用户应得奖金 发放金额小于0.01元则
                        $self_reward = floor($person_get * $self_jgz);
                        if ($self_reward < 1) {
                            continue;
                        }
                        $arr[$key]['reward'] = $self_reward;
                        $send_reward += $self_reward;
                }
            
        }

        //当前帐号所属店铺 或者超管选择店铺 团队奖励名称
        if($store_id == 0){
            $awardName = '富利指数';
        }else{
            $teamAward = new TeamAward;
            $team = $teamAward->awardGold($store_id);
            $awardName = $team->award_name;
        }
        if(!empty($request->report)){
            return Excel::download(new OnePoolExport($arr), 'one_pool.xlsx');
        }

        $data = [];
        $data['data'] = $arr;// 每人数据
        $data['total'] = count($arr);// 总人数
        $data['reward'] = $poolSum;// 总奖金
        $data['jgz'] = $amountSum;// 总军功章
        $data['person_get'] = $person_get;// 军功章单价
        $data['send_reward'] = $send_reward;// 放出的奖金, 与应发放奖金有一定的差值
        $data['awardName'] = $awardName;// 团队奖励名称
        $data['path'] = env('APP_URL').'/member/jgz_list';
        return $this->success($data);
    }

    public function jgz_send(Request $request)
    {
        $User = new User;
        $Order = new Order;
        $DealRecord = new DealRecord;
        $pool = new TotalBonusPool;
        
        // 读取店铺ID
        $user = Auth::guard('admin')->user();
        if ($user->store_id === 0) {
            // 超管必需选择店铺
            $store_id = $request['storeId'];
            if (empty($store_id)) {
                return self::errorClient(['info' => '请输入店铺ID']);
            }
        } else {
            // 否则 获取用户本身代表的店铺
            $store_id = $user->store_id;
        }

        $beg = date('Y-m-1 00:00:00',strtotime('last month'));
        $end = date('Y-m-d 23:59:59',strtotime(date('Y-m-1').'-1 day'));
        
        $min_level_arr = TeamAward::where('store_id', $store_id)->first();

        //上个月总军功章  需要结算的总军功章
        $user_send = $DealRecord->join('users as u','u.id',"=",'deal_records.user_id')
         ->where('deal_records.store_id',$store_id)->where('deal_records.jm_type',3)->where('deal_records.status',3)->where('deal_records.is_set',0)->whereBetween('deal_records.created_at',[$beg, $end])
         ->groupBy('deal_records.user_id')
         ->select('u.id',DB::raw('SUM(deal_records.amount) as amountSum'),'u.gold','u.grade','u.jgz','u.grade_at','u.is_partner','u.partner_at')
         ->get()->toArray();
        
        $userIds = [];
        foreach ($user_send as $key => $value) {
            //VIP
                if($value['grade'] >= $min_level_arr['min_level'] && $value['grade_at'] <= $end){
                    //需要发放奖金的用户
                    array_push($userIds,$value['id']);
                }
                //合伙人
                if($value['is_partner'] == 1 && $value['partner_at'] <= $end){
                    //需要发放奖金的用户
                    array_push($userIds,$value['id']);
                }
        }
        $userIds = array_unique($userIds);
        $amountSum = $DealRecord->whereIn('user_id',$userIds)->where('store_id',$store_id)->where('jm_type',3)->where('status',3)->where('is_set',0)->whereBetween('created_at',[$beg, $end])->sum('amount');
        $amountSum = $amountSum/100;
        if ($amountSum == 0) {
            return self::errorClient(['info' => $min_level_arr['award_name'].'为0，无可发放内容']);
        }
        
        //上个月总奖金  1号奖金池总计
        $poolModel = $DealRecord->where('store_id',$store_id)->whereIn('deal_type',[21,30])->where('status',3)->where('is_set',0)->whereBetween('created_at',[$beg, $end]);
        $poolSum = $poolModel->sum('amount');
        $poolSum = $poolSum/100;

        //上个月所有富力指数及1号奖金池记录ID 更新结算状态
        $dealModel = $DealRecord->where('store_id',$store_id)->where('jm_type',3)->where('status',3)->where('is_set',0)->whereBetween('created_at',[$beg, $end]);
        $flist = $dealModel->select('id')->get()->toArray();
        $fIds = array_column($flist,'id');

        $plist = $poolModel->select('id')->get()->toArray();
        $pIds = array_column($plist,'id');
        $dealIds = array_unique(array_merge($fIds,$pIds));

        //保留三位小数  不四舍五入  小数位取小数点后三位
        $num = ($poolSum/$amountSum)*1000;
        if($num >= 1){
            $person_get = floor($num)/1000;
        }else{
            $person_get = 0;
        }
        $send_reward = 0;// 发放出的奖金, 与应发放奖金有一定的差值, 得到差值 并 进行处理
        $arr = [];
        $jgz_record = [];// 军功章折换余额记录
        $jgz_re = [];// 军功章扣除记录
        DB::beginTransaction();
        try {
            foreach ($user_send as $key => $value) {

                // 军功章扣除记录生成
                $jgz_re['type'] = 'out';
                $jgz_re['store_id'] = $store_id;
                $jgz_re['user_id'] = $value['id'];
                $jgz_re['status'] = 1;
                $jgz_re['reason'] = $min_level_arr['award_name'].'扣除';
                $jgz_re['deal_type'] = 20;// 军功章折算余额
                $jgz_re['deal_item_id'] = 0;
                $jgz_re['order_type'] = 5;
                $jgz_re['jm_type'] = 3;
                $jgz_re['grade'] = $value['grade'];
                $jgz_re['mark'] = '';
                $jgz_re['amount'] = $value['amountSum'];
                $jgz_re['created_at'] = date('Y-m-d H:i:s');
                $jgz_re['last_balance'] = $value['jgz'];
                $new_balance = $value['jgz'] - $value['amountSum'];
                $jgz_re['new_balance'] = $new_balance;
                $goldresult = $DealRecord->deductMoney($jgz_re);
                if ($goldresult['code'] != 20000) {
                    return $goldresult;
                }

                if(in_array($value['id'],$userIds)){
                    // 遍历得出 用户应得奖金 发放金额小于0.01元则
                    $self_jgz = $value['amountSum'] / 100;
                    $self_reward = floor($person_get * $self_jgz);
                    if ($self_reward < 1) {
                        continue;
                    }
                    $arr[$value['id']]['id'] = $value['id'];
                    $arr[$value['id']]['jgz'] = $value['amountSum'] / 100;
                    $arr[$value['id']]['reward'] = $self_reward;
                    $send_reward += $self_reward;
                    // 奖金发放
                    $jgz_record['store_id'] = $store_id;
                    $jgz_record['user_id'] = $value['id'];
                    $jgz_record['status'] = 3;
                    $jgz_record['reason'] = $min_level_arr['award_name'].'发放';
                    $jgz_record['deal_item_id'] = 0;
                    $jgz_record['order_type'] = 5;
                    $jgz_record['grade'] = $value['grade'];
                    $jgz_record['mark'] = '';

                    $jgz_record['deal_type'] = 10;// 军功章折算余额
                    $jgz_record['jm_type'] = 1;
                    $jgz_record['amount'] = $self_reward*100;
                    $jgz_record['last_balance'] = $value['gold'];
                    $goldreturned = $DealRecord->returnedMoney($jgz_record);
                    if ($goldreturned['code'] != 20000) {
                        return $goldreturned;
                    }
                }
            }
            //1号奖金池金额更新 交易记录及1号奖金池总金额更新
            $dealGold = [];
            $dealGold['store_id'] = $store_id;
            $dealGold['status'] = 1;
            $dealGold['deal_item_id'] = '';
            $dealGold['order_type'] = 5;// 会员订单
            $dealGold['jm_type'] = 1;// 余额
            $dealGold['user_id'] = 1;//奖金池收入 不更新用户表余额
            $dealGold['grade'] = 0;
            $dealGold['mark'] = date('Ymd').'富利指数结算,会员折扣发放当月累计金额(发放剩余累计在会员折扣)';
            $dealGold['amount'] = $send_reward*100;
            $dealGold['reason'] = '会员折扣扣除';
            $dealGold['deal_type'] = 26;// 1号奖金池金额扣除
            $poolresult = $DealRecord->deductMoney($dealGold, 1);
            if ($poolresult['code'] != 20000) {
                return $poolresult;
            }
            //已结算的富利指数交易记录状态已更新
            $dealresult = $DealRecord->whereIn('id',$dealIds)->update(['is_set'=>1]);
            if ($poolresult && $dealresult) {
                DB::commit();
                return self::successClient(['info' => '结算成功']);
            } else {
                return self::errorClient(['info' => '结算失败']);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return $e;
            return $e->getLine().$e->getMessage();
        }
    }
    public function getList(Request $request)
    {
        $pageSize = $request['pageSize'];
        $storeId = $request['storeId'];
        $userId = $request['userId'];
        $phone = $request['phone'];
        $grade = $request['grade'];
        $report = $request['report'];

        $userModel = new User;
        $data = $userModel->getList($pageSize, $storeId, $phone, $userId, $grade, $report);

        return $data;
    }

    public function handle(Request $request)
    {
        $id = $request['id'];
        $data = $request['data'];
        $type = $request['type'];
        $handleType = $request['handleType'];
        $mark = $request['mark'];

        $userModel = new User;
        $data = $userModel->handle($id, $data, $type, $handleType, $mark);

        return $data;
    }

    public function getTree(Request $request)
    {
        $storeId = $request['storeId'];
        $userId = $request['userId'];
        if (empty($userId)) {
            $userId = 1;
        }

        $userModel = new User;
        $data = $userModel->getTree($storeId, $userId);

        return $data;
    }

    //月度合伙人结算列表
    public function teamMonthList(Request $request){
         // 读取店铺ID
         $user = Auth::guard('admin')->user();
         if ($user->store_id === 0) {
             // 超管必需选择店铺
             $store_id = $request['storeId'];
             if (empty($store_id)) {
                 return self::errorClient(['info' => '请输入店铺ID'.$store_id]);
             }
         } else {
             // 否则 获取用户本身代表的店铺
             $store_id = $user->store_id;
         }
         $deal = new DealRecord;
         $beg = date('Y-m-1 00:00:00',strtotime('last month'));
         $end = date('Y-m-d 23:59:59',strtotime(date('Y-m-1').'-1 day'));

         //获取上月月度合伙人总奖金
         $teamMonthSum = $deal->getAmountSum($store_id,22,$beg,$end)/100;
         //获取上月推荐合伙人总奖金
         $teamRecommend = $deal->getAmountSum($store_id,24,$beg,$end)/100;
         
         if($teamMonthSum == 0 && $teamRecommend == 0){
            return self::errorClient(['info' => '没有金额需要发放']);
         }  

         //获取每个用户生成的月度合伙人总奖金
         $userMonth = $deal->userAmountSum($store_id,22,$beg,$end);

         //获取每个用户生成的推荐合伙人总奖金
         $userRecommend = $deal->userAmountSum($store_id,24,$beg,$end);

         //合伙人应获取的月度合伙人奖金和推荐合伙人奖金
         $arr = $deal->teamData($userMonth,$userRecommend);
         foreach ($arr as $key => $value) {
             $arr[$key]['month'] = $value['month']/100; 
             $arr[$key]['recommend'] = $value['recommend']/100; 
         }

         if(!empty($request->report)){
            return $deal->handleImportTeamMonthData($store_id,$beg,$end);
         }

         $data = [];
         $data['monthSum'] = $teamMonthSum;
         $data['recommendSum'] = $teamRecommend;
         $data['path'] = env('APP_URL').'/member/team_month_list';
         $data['data'] = array_values($arr);
         return $this->success($data); 
    }

    //月度合伙人结算发放
    public function teamMonthSend(Request $request){
        // 读取店铺ID
        $user = Auth::guard('admin')->user();
        if ($user->store_id === 0) {
            // 超管必需选择店铺
            $store_id = $request['storeId'];
            if (empty($store_id)) {
                return self::errorClient(['info' => '请输入店铺ID'.$store_id]);
            }
        } else {
            // 否则 获取用户本身代表的店铺
            $store_id = $user->store_id;
        }
        
        $deal = new DealRecord;
        $result= $deal->teamMonthSend($store_id);
        return $result;
    }

    //店铺总金额
    public function goldSum(Request $request){
        // 读取店铺ID
        $user = Auth::guard('admin')->user();
        if ($user->store_id === 0) {
            // 超管必需选择店铺
            $store_id = $request['storeId'];
            if (empty($store_id)) {
                return self::errorClient(['info' => '请输入店铺ID'.$store_id]);
            }
        } else {
            // 否则 获取用户本身代表的店铺
            $store_id = $user->store_id;
        }

        if(!empty($request->report)){
            $deal = new DealRecord;
            return $deal->handleImportBonusData($store_id,$request->type);
        }

        $pool = new TotalBonusPool;
        $bonus = $pool->where('store_id',$store_id)->first();
        //公司账号余额
        $user = new User;
        $company = $user->where('id',1)->first();
        
        $data = [];
        $info = [];
        $arr = [];
        $arr['store_id'] = $store_id;
        $arr['gold_sum'] = $company->gold/100;
        $arr['bonus_pool_one_sum'] = $bonus->bonus_pool_one_sum/100;
        $arr['team_month_sum'] = $bonus->team_month_sum/100;
        $arr['team_year_sum'] = $bonus->team_year_sum/100;
        $arr['team_recommend_sum'] = $bonus->team_recommend_sum/100;
        $arr['team_fund_sum'] = $bonus->team_fund_sum/100;
        $arr['bd_referrer_sum'] = $bonus->bd_referrer_sum/100;
        $arr['bd_provident_fund_sum'] = $bonus->bd_provident_fund_sum/100;
        $arr['bd_member_pool_sum'] = $bonus->bd_member_pool_sum/100;
        $arr['bd_order_pool_sum'] = $bonus->bd_order_pool_sum/100;
        $arr['total'] =  $arr['gold_sum'] + $arr['bonus_pool_one_sum'] + $arr['team_month_sum']
         + $arr['team_year_sum'] + $arr['team_recommend_sum'] + $arr['team_fund_sum']
         + $arr['bd_referrer_sum'] + $arr['bd_provident_fund_sum'] + $arr['bd_member_pool_sum'] + $arr['bd_order_pool_sum'];
        array_push($info,$arr);
        $data['data'] = $info;
        $data['path'] = env('APP_URL').'/member/gold_sum';
        return $this->success($data);
    }

    //扣除公司账号余额
    public function deduct(Request $request){
        $data = $request->data;
        $reason = $request->reason;
        $DealRecord = new DealRecord;
        $dealGold = [];
        $dealGold['store_id'] = 3;
        $dealGold['status'] = 1;
        $dealGold['deal_item_id'] = 0;
        $dealGold['order_type'] = 4;// 会员订单
        $dealGold['jm_type'] = 1;
        $dealGold['user_id'] = 1;
        $dealGold['grade'] = 0;
        $dealGold['mark'] = $reason;
        $dealGold['amount'] = $data*100;
        $dealGold['reason'] = '公司余额扣除';
        $dealGold['deal_type'] = 34;
        $goldReturned = $DealRecord->deductMoney($dealGold);
        if ($goldReturned['code'] != 20000) {
            return $goldReturned;
        }
        return $this->success("操作成功");
    }



    //每日金额
    public function dailyAmount(Request $request){
        // 读取店铺ID
        $user = Auth::guard('admin')->user();
        if ($user->store_id === 0) {
            // 超管必需选择店铺
            $store_id = $request['storeId'];
            if (empty($store_id)) {
                return self::errorClient(['info' => '请输入店铺ID'.$store_id]);
            }
        } else {
            // 否则 获取用户本身代表的店铺
            $store_id = $user->store_id;
        }

        $amount = new DailyAmount;
        $list = $amount->where('store_id',$store_id)->orderBy('created_time','desc')->get()->toArray();
        $data = [];
        foreach ($list as $key => $value) {
            $list[$key]['gold'] = $value['gold']/100;
            $list[$key]['member_gold'] = $value['member_gold']/100;
            $list[$key]['bonus_pool_one'] = $value['bonus_pool_one']/100;
            $list[$key]['team_month'] = $value['team_month']/100;
            $list[$key]['team_year'] = $value['team_year']/100;
            $list[$key]['team_recommend'] = $value['team_recommend']/100;
            $list[$key]['team_fund'] = $value['team_fund']/100;
        }
        if(!empty($request['report'])) {
            return Excel::download(new DailyAmountExport($list), 'DailyAmount.xlsx');
        }
        $data['data'] = $list;
        $data['path'] = env('APP_URL').'/member/daily_amount';
        return $this->success($data);
    }

    public function transferList(Request $request){
        // 读取店铺ID
        $user = Auth::guard('admin')->user();
        if ($user->store_id === 0) {
            // 超管必需选择店铺
            $store_id = $request['storeId'];
            if (empty($store_id)) {
                return self::errorClient(['info' => '请输入店铺ID'.$store_id]);
            }
        } else {
            // 否则 获取用户本身代表的店铺
            $store_id = $user->store_id;
        }
        $deal = new DealRecord;
        $amount = $deal->surplusAmount($store_id,$request->type);
        return $this->success($amount);
    }

    public function transfer(Request $request){
        $store_id = $request->storeId;
        $deal = new DealRecord;
        return $deal->transfer($store_id,$request->type,$request->user_id,$request->reason,$request->amount);
    }


    //富力惠列表
    public function flhList(Request $request){
        // 读取店铺ID
        $user = Auth::guard('admin')->user();
        if ($user->store_id === 0) {
            // 超管必需选择店铺
            $store_id = $request['storeId'];
            if (empty($store_id)) {
                return self::errorClient(['info' => '请输入店铺ID'.$store_id]);
            }
        } else {
            // 否则 获取用户本身代表的店铺
            $store_id = $user->store_id;
        }

        $deal_record = new DealRecord;
        $data = $deal_record->flhList($store_id,$request->report);
        return $data;
    }

    //富力惠发放
    public function flhSend(Request $request){
        // 读取店铺ID
        $user = Auth::guard('admin')->user();
        if ($user->store_id === 0) {
            // 超管必需选择店铺
            $store_id = $request['storeId'];
            if (empty($store_id)) {
                return self::errorClient(['info' => '请输入店铺ID'.$store_id]);
            }
        } else {
            // 否则 获取用户本身代表的店铺
            $store_id = $user->store_id;
        }
        
        $deal = new DealRecord;
        $result= $deal->flhSend($store_id);
        return $result;
    }


    //虹包列表
    public function bdMemPoolList(Request $request)
    {   
        if(!empty($request['checkedUsers'])) $request['checkedUsers'] = [];
        $result = $this->bdData($request);
        if ($result['code'] != 20000) {
            return $result;
        }
        $store_id = $result['data']['store_id'];
        $user_send = $result['data']['user_send'];
        $userIds = $result['data']['userIds'];
        $amountSum = $result['data']['amountSum'];
        $poolSum = $result['data']['poolSum'];
        $person_get = $result['data']['person_get'];
        
        $grade = new Grade;
        $gradeInfo = $grade->gradeOptions($store_id);
        
        $send_reward = 0;// 发放出的奖金, 与应发放奖金有一定的差值, 得到差值 并 进行处理
        $arr = [];
        foreach ($user_send as $key => $value) {
                        $self_amount = $value['amountSum'] / 100;
                        $arr[$key]['store_id'] = $store_id;
                        $arr[$key]['id'] = $value['id'];
                        $arr[$key]['grade'] = '会员';
                        $arr[$key]['bd_index'] = $self_amount;
                        $arr[$key]['reward'] = 0;
                if(in_array($value['id'],$userIds)){
                        $arr[$key]['grade'] = $gradeInfo[$value['grade']]['label'];
                        // 遍历得出 用户应得奖金 发放金额小于0.01元则
                        $self_reward = floor($person_get * $self_amount);
                        if ($self_reward < 1) {
                            continue;
                        }
                        $arr[$key]['reward'] = $self_reward;
                        $send_reward += $self_reward;
                }
            
        }

        //当前帐号所属店铺 或者超管选择店铺 团队奖励名称
        if($store_id == 0){
            $awardName = '报单指数';
        }else{
            $teamAward = new TeamAward;
            $team = $teamAward->awardGold($store_id);
            $awardName = $team->bd_award_name;
        }
        if(!empty($request->report)){
            return Excel::download(new BdMemPoolExport($arr), '红包发放.xlsx');
        }

        $data = [];
        $data['data'] = $arr;// 每人数据
        $data['total'] = count($arr);// 总人数
        $data['reward'] = $poolSum;// 总奖金
        $data['bd_index'] = $amountSum;// 总报单指数
        $data['person_get'] = $person_get;// 报单指数单价
        $data['send_reward'] = $send_reward;// 放出的奖金, 与应发放奖金有一定的差值
        $data['awardName'] = $awardName;// 团队奖励名称
        $data['path'] = env('APP_URL').'/member/bdmem_list';
        return $this->success($data);
    }
    public function bdData($request){
                 // 读取店铺ID
                 $user = Auth::guard('admin')->user();
                 if ($user->store_id === 0) {
                     // 超管必需选择店铺
                     $store_id = $request['storeId'];
                     if (empty($store_id)) {
                         return self::errorClient(['info' => '请输入店铺ID'.$store_id]);
                     }
                 } else {
                     // 否则 获取用户本身代表的店铺
                     $store_id = $user->store_id;
                 }
                 $begin_at = $request['begin_at'];
                 $end_at = $request['end_at'];
                 if(date('Y-m-d H:i:s',strtotime($begin_at)) !== $begin_at || date('Y-m-d H:i:s',strtotime($end_at)) !== $end_at){
                    return self::errorClient(['info' => '请选择时间'.$store_id]);
                }
                 $deal = new DealRecord;
                 $min_level_arr = TeamAward::where('store_id', $store_id)->first();
                 $check_send = [];
                 if($request['checkAll'] !== true && !empty($request['checkedUsers'])){
                    $checkIds = [];
                    foreach($request['checkedUsers'] as $item){
                        $itemArr = json_decode($item,true);
                        $checkIds[] = $itemArr['id'];
                    }
                    $check_send = $deal->join('users as u','u.id',"=",'deal_records.user_id')
                    ->where('deal_records.store_id',$store_id)->where('deal_records.jm_type',4)->where('deal_records.status',3)->where('deal_records.is_set',0)->whereBetween('deal_records.created_at',[$begin_at, $end_at])
                    ->whereIn('u.id',$checkIds)
                    ->groupBy('deal_records.user_id')
                    ->select('u.id',DB::raw('SUM(deal_records.amount) as amountSum'),'u.gold','u.grade','u.bd_index','u.grade_at','u.is_partner','u.partner_at')
                    ->get()->toArray();
                 }
                 //需要结算的总军功章
                 $user_send = $deal->join('users as u','u.id',"=",'deal_records.user_id')
                 ->where('deal_records.store_id',$store_id)->where('deal_records.jm_type',4)->where('deal_records.status',3)->where('deal_records.is_set',0)->whereBetween('deal_records.created_at',[$begin_at, $end_at])
                 ->groupBy('deal_records.user_id')
                 ->select('u.id',DB::raw('SUM(deal_records.amount) as amountSum'),'u.gold','u.grade','u.bd_index','u.grade_at','u.is_partner','u.partner_at')
                 ->get()->toArray();
                 
                 $conform_user = $user_send;
                 if(!empty($check_send)){
                    $conform_user = $check_send; 
                 }
                 $userIds = [];
                 foreach ($conform_user as $key => $value) {
                     //VIP
                         if($value['grade'] >= $min_level_arr['bd_min_level'] && $value['grade_at'] <= $end_at){
                             //需要发放奖金的用户
                             array_push($userIds,$value['id']);
                         }
                         //合伙人
                         if($value['is_partner'] == 1 && $value['partner_at'] <= $end_at){
                             //需要发放奖金的用户
                             array_push($userIds,$value['id']);
                         }
                 }
                 $userIds = array_unique($userIds);
                 $amountSum = $deal->whereIn('user_id',$userIds)->where('store_id',$store_id)->where('jm_type',4)->where('status',3)->where('is_set',0)->whereBetween('created_at',[$begin_at, $end_at])->sum('amount');
                 $amountSum = $amountSum/100;
                 if ($amountSum == 0) {
                     return self::errorClient(['info' => $min_level_arr['bd_award_name'].'为0，无可发放内容']);
                 }
                 
                 //虹包奖金池总计
                 $poolModel = $deal->where('store_id',$store_id)->whereIn('deal_type',[56])->where('status',3)->where('is_set',0)->whereBetween('created_at',[$begin_at, $end_at]);
                 $poolSum = $poolModel->sum('amount');
                 $poolSum = $poolSum/100;
                //待结算记录ID
                $dealModel = $deal->where('store_id',$store_id)->where('jm_type',4)->where('status',3)->where('is_set',0)->whereBetween('created_at',[$begin_at, $end_at]);
                $flist = $dealModel->select('id')->get()->toArray();
                $fIds = array_column($flist,'id');
        
                $plist = $poolModel->select('id')->get()->toArray();
                $pIds = array_column($plist,'id');
                $dealIds = array_unique(array_merge($fIds,$pIds));
        
                //保留两位小数  不四舍五入  小数位取小数点后两位
                $num = ($poolSum/$amountSum)*1000;
                if($num >= 1){
                    $person_get = floor($num)/1000;
                }else{
                    $person_get = 0;
                }
                $arr = [];
                $arr['store_id'] = $store_id;
                $arr['user_send'] = $user_send;
                $arr['userIds'] = $userIds;
                $arr['amountSum'] = $amountSum;
                $arr['poolSum'] = $poolSum;
                $arr['person_get'] = $person_get;
                $arr['min_level_arr'] = $min_level_arr;
                $arr['dealIds'] = $dealIds;
                return self::successClient($arr);
    }
    //虹包列表
    public function bdMemPoolSend(Request $request){
        if(empty($request['checkedUsers'])){
            return self::errorClient(['info' => '请选择发放用户']);
        }
        $result = $this->bdData($request);
        if ($result['code'] != 20000) {
            return $result;
        }
        $store_id = $result['data']['store_id'];
        $user_send = $result['data']['user_send'];
        $userIds = $result['data']['userIds'];
        $amountSum = $result['data']['amountSum'];
        $poolSum = $result['data']['poolSum'];
        $person_get = $result['data']['person_get'];
        $min_level_arr = $result['data']['min_level_arr'];
        $dealIds = $result['data']['dealIds'];
        $deal = new DealRecord;
        $send_reward = 0;// 发放出的奖金, 与应发放奖金有一定的差值, 得到差值 并 进行处理
        $arr = [];
        $bd_in = [];// 军功章折换余额记录
        $bd_out = [];// 军功章扣除记录
        DB::beginTransaction();
        try {
            foreach ($user_send as $key => $value) {

                // 军功章扣除记录生成
                $bd_out['type'] = 'out';
                $bd_out['store_id'] = $store_id;
                $bd_out['user_id'] = $value['id'];
                $bd_out['status'] = 1;
                $bd_out['reason'] = $min_level_arr['bd_award_name'].'扣除';
                $bd_out['deal_type'] = 62;// 报单指数结算扣除
                $bd_out['deal_item_id'] = 0;
                $bd_out['order_type'] = 6;//报单指数结算订单
                $bd_out['jm_type'] = 4;
                $bd_out['grade'] = $value['grade'];
                $bd_out['mark'] = '';
                $bd_out['amount'] = $value['amountSum'];
                $bd_out['created_at'] = date('Y-m-d H:i:s');
                $bd_out['last_balance'] = $value['bd_index'];
                $new_balance = $value['bd_index'] - $value['amountSum'];
                $bd_out['new_balance'] = $new_balance;
                $goldresult = $deal->deductMoney($bd_out);
                if ($goldresult['code'] != 20000) {
                    return $goldresult;
                }

                if(in_array($value['id'],$userIds)){
                    // 遍历得出 用户应得奖金 发放金额小于0.01元则
                    $self_bd = $value['amountSum'] / 100;
                    $self_reward = floor($person_get * $self_bd);
                    if ($self_reward < 1) {
                        continue;
                    }
                    $arr[$value['id']]['id'] = $value['id'];
                    $arr[$value['id']]['bd_index'] = $value['amountSum'] / 100;
                    $arr[$value['id']]['reward'] = $self_reward;
                    $send_reward += $self_reward;
                    // 奖金发放
                    $bd_in['store_id'] = $store_id;
                    $bd_in['user_id'] = $value['id'];
                    $bd_in['status'] = 3;
                    $bd_in['reason'] = $min_level_arr['bd_award_name'].'发放';
                    $bd_in['deal_item_id'] = 0;
                    $bd_in['order_type'] = 6;
                    $bd_in['grade'] = $value['grade'];
                    $bd_in['mark'] = '';

                    $bd_in['deal_type'] = 63;//报单指数折算为余额
                    $bd_in['jm_type'] = 1;
                    $bd_in['amount'] = $self_reward*100;
                    $bd_in['last_balance'] = $value['gold'];
                    $goldreturned = $deal->returnedMoney($bd_in);
                    if ($goldreturned['code'] != 20000) {
                        return $goldreturned;
                    }
                }
            }
            //虹包池金额更新 交易记录及虹包池总金额更新
            $dealGold = [];
            $dealGold['store_id'] = $store_id;
            $dealGold['status'] = 1;
            $dealGold['deal_item_id'] = '';
            $dealGold['order_type'] = 6;// 会员订单
            $dealGold['jm_type'] = 1;// 余额
            $dealGold['user_id'] = 1;//奖金池收入 不更新用户表余额
            $dealGold['grade'] = 0;
            $dealGold['mark'] = date('Ymd').'报单指数结算,虹包发放累计金额(发放剩余累计在虹包)';
            $dealGold['amount'] = $send_reward*100;
            $dealGold['reason'] = '虹包扣除';
            $dealGold['deal_type'] = 57;// 虹包池金额扣除
            $poolresult = $deal->deductMoney($dealGold, 8);
            if ($poolresult['code'] != 20000) {
                return $poolresult;
            }
            //已结算的报单指数交易记录状态已更新
            $dealresult = $deal->whereIn('id',$dealIds)->update(['is_set'=>1]);
            if ($poolresult && $dealresult) {
                DB::commit();
                return self::successClient(['info' => '结算成功']);
            } else {
                return self::errorClient(['info' => '结算失败']);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return $e;
            return $e->getLine().$e->getMessage();
        }
 
    }

    //分虹列表
    public function bdOrderPoolList(Request $request)
    {
        $result = $this->bdOrderData($request);
        if ($result['code'] != 20000) {
            return $result;
        }
        $store_id = $result['data']['store_id'];
        $reward = $result['data']['reward'];
        $user_send = $result['data']['user_send'];
        
        $send_reward = 0;
        $valueArr = [];
        $arr = [];
        foreach ($user_send as $key => $value) {
                if($value['deal_get_id'] > 0){
                        $valueArr['store_id'] = $store_id;
                        $valueArr['id'] = $value['deal_get_id'];
                        $valueArr['grade'] = '合伙人';
                        $valueArr['reward'] = $value['amountSum']/100;
                        array_push($arr,$valueArr);
                        $send_reward += $value['amountSum'];
                }
        }

        if(!empty($request->report)){
            return Excel::download(new BdOrderPoolExport($arr), '分虹.xlsx');
        }

        $data = [];
        $data['data'] = $arr;// 每人数据
        $data['reward'] = $reward/100;// 总奖金
        $data['send_reward'] = $send_reward/100;// 放出的奖金, 与应发放奖金有一定的差值
        $data['path'] = env('APP_URL').'/member/bdorder_list';
        return $this->success($data);
    }
    public function bdOrderData($request){
                 // 读取店铺ID
                 $user = Auth::guard('admin')->user();
                 if ($user->store_id === 0) {
                     // 超管必需选择店铺
                     $store_id = $request['storeId'];
                     if (empty($store_id)) {
                         return self::errorClient(['info' => '请输入店铺ID'.$store_id]);
                     }
                 } else {
                     // 否则 获取用户本身代表的店铺
                     $store_id = $user->store_id;
                 }
                 $begin_at = $request['begin_at'];
                 $end_at = $request['end_at'];
                 if(date('Y-m-d H:i:s',strtotime($begin_at)) !== $begin_at || date('Y-m-d H:i:s',strtotime($end_at)) !== $end_at){
                    return self::errorClient(['info' => '请选择时间'.$store_id]);
                }
                 $deal = new DealRecord;
                  
                //分虹总金额
                $fhTotal = $deal->where('store_id',$store_id)
                ->where('jm_type',1)
                ->where('status',3)
                ->where('is_set',0)
                ->where('deal_type',59)
                ->whereBetween('created_at',[$begin_at, $end_at])
                ->groupBy('deal_get_id')
                ->select(DB::raw('SUM(amount) as amountSum'),'deal_get_id')
                ->get()->toArray();

                $amountSumArr = array_column($fhTotal,'amountSum'); 
                $reward = array_sum($amountSumArr);
                $arr = [];
                $arr['store_id'] = $store_id;
                $arr['reward'] = $reward;
                $arr['user_send'] = $fhTotal;
                $arr['begin_at'] = $begin_at;
                $arr['end_at'] = $end_at;
                return self::successClient($arr);
    }
    //分虹列表
    public function bdOrderPoolSend(Request $request){
        $result = $this->bdOrderData($request);
        if ($result['code'] != 20000) {
            return $result;
        }
        $store_id = $result['data']['store_id'];
        $user_send = $result['data']['user_send'];
        $begin_at = $result['data']['begin_at'];
        $end_at = $result['data']['end_at'];
        $sendArr = array_filter($user_send, function($item){
            return $item['deal_get_id'] > 0;
        });
        $deal = new DealRecord;
        //分虹记录ID
        $fhId = $deal->where('store_id',$store_id)
        ->where('jm_type',1)
        ->where('status',3)
        ->where('is_set',0)
        ->where('deal_type',59)
        ->whereBetween('created_at',[$begin_at, $end_at])
        ->select('id')
        ->get()->toArray();
        $send_reward = 0;// 发放出的奖金, 与应发放奖金有一定的差值, 得到差值 并 进行处理
        $arr = [];
        DB::beginTransaction();
        try {
            foreach ($sendArr as $key => $value) {
                // 奖金发放
                $bd_in['store_id'] = $store_id;
                $bd_in['user_id'] = $value['deal_get_id'];
                $bd_in['status'] = 3;
                $bd_in['reason'] = '分虹发放';
                $bd_in['deal_item_id'] = 0;
                $bd_in['order_type'] = 3;
                $bd_in['grade'] = 0;
                $bd_in['mark'] = '';
                $bd_in['deal_type'] = 64;//报单指数折算为余额
                $bd_in['jm_type'] = 1;
                $bd_in['amount'] = $value['amountSum'];
                $send_reward += $value['amountSum'];
                $goldreturned = $deal->returnedMoney($bd_in);
                if ($goldreturned['code'] != 20000) {
                    return $goldreturned;
                }
                
            }
            //虹包池金额更新 交易记录及虹包池总金额更新
            $dealGold = [];
            $dealGold['store_id'] = $store_id;
            $dealGold['status'] = 1;
            $dealGold['deal_item_id'] = '';
            $dealGold['order_type'] = 3;// 会员订单
            $dealGold['jm_type'] = 1;// 余额
            $dealGold['user_id'] = 1;//奖金池收入 不更新用户表余额
            $dealGold['grade'] = 0;
            $dealGold['mark'] = date('Ymd').'分虹结算,分虹发放累计金额(发放剩余累计在分虹)';
            $dealGold['amount'] = $send_reward;
            $dealGold['reason'] = '分虹扣除';
            $dealGold['deal_type'] = 60;// 虹包池金额扣除
            $poolresult = $deal->deductMoney($dealGold, 9);
            if ($poolresult['code'] != 20000) {
                return $poolresult;
            }
            //已结算的报单指数交易记录状态已更新
            $dealresult = $deal->whereIn('id',$fhId)->update(['is_set'=>1]);
            if ($poolresult && $dealresult) {
                DB::commit();
                return self::successClient(['info' => '结算成功']);
            } else {
                return self::errorClient(['info' => '结算失败']);
            }
        } catch (\Exception $e) {
            DB::rollBack();
            return $e;
            return $e->getLine().$e->getMessage();
        }
 
    }

    public function getImportUrl(){
        $data = [];
        $data['path'] = env('APP_URL').'/member/userimport';
        $data['exportpath'] = env('APP_URL').'/member/usertemplate_export';
        return $this->success($data);
    }

    public function userImport(Request $request){
        if(!$request->hasFile('file')){
            exit('上传文件为空！');
        }

        try {
            $import = new UserImport;
            $result = Excel::import($import, $request->file('file'));
            return $this->success([
                'message' => '用户导入成功',
                'root_user' => [
                    'phone' => $import->getRootUser()->phone,
                    'level' => $import->getRootUser()->level
                ],
                'result' => [
                    'success_count' => $import->getSuccessCount(),
                    'skipped_count' => $import->getSkippedCount(),
                    'failed_count' => $import->getFailedCount(),
                    'failed_rows' => $import->getFailedRows()
                ]
            ]); 
        } catch (\Exception $e) {
            return $this->error([
                'message' => $e->getMessage(),
                'errors' => method_exists($e, 'errors') ? $e->errors() : []
            ]); 
        }    
    }
    //下载excel用户导入模版
    public function userTemplateExport(){
        $data = [
            [13800138001, "pass123", "", 1],
            [13800138002, "pass456", 13800138001, 2],
            [13800138003, "pass789", 13800138001, 1],
            [13800138004, "passabc", 13800138003, 1],
            [13800138005, "passdef", 13800138004, 1]
        ];
        return Excel::download(new UserTemplateExport($data), 'excel用户导入模版.xlsx');
    }
}
